/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.mapper.BaseMapper;
import org.jbase.admin.dao.AdminMenuDao;
import org.jbase.admin.dao.AdminRoleMenuDao;
import org.jbase.admin.entity.AdminMenu;
import org.jbase.admin.security.ShiroUtils;
import org.jbase.common.service.EntityMapperService;
import org.jbase.common.utils.Pager;
import org.jbase.common.utils.message.Message;
import org.jbase.common.utils.message.MessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project: jbase-springboot <br/>
 * File: AdminMenuService.java <br/>
 * Class: org.jbase.admin.service.AdminMenuService <br/>
 * Description: 系统菜单. <br/>
 * Copyright: Copyright (c) 2016 <br/>
 * Company: http://git.oschina.net/liuzp315/Jbase <br/>
 * Makedate: 2016-12-29 12:19:49 <br/>
 * gen by Jbase Coder <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
@Service
public class AdminMenuService extends EntityMapperService<AdminMenu> {

	@Autowired
	private AdminMenuDao adminMenuDao;

	@Autowired
	private AdminRoleMenuDao adminRoleMenuDao;

	@Override
	public BaseMapper<AdminMenu> dao() {
		return adminMenuDao;
	}

	public Pager query(Map<String, String> map, Pager pager) {

		PageQuery<Object> pageQuery = new PageQuery<Object>(pager.getPageNumber(), map, -1, pager.getPageSize());
		adminMenuDao.selectPager(pageQuery);

		pager.setList(pageQuery.getList());
		pager.setRecordCount((int) pageQuery.getTotalRow());
		return pager;
	}

	public AdminMenu fetchBySid(String sid) {
		return adminMenuDao.fetchBySid(sid);
	}

	public void deleteBySid(String sid) {
		adminMenuDao.deleteBySid(sid);
	}

	public Message<List<AdminMenu>> listBySids(String sids) {
		Message<List<AdminMenu>> mess = new Message<>();
		mess.SetMessageCode(MessageCode.SUCCESS);
		mess.setSuccess(true);

		if (StringUtils.isBlank(sids)) {
			return mess;
		}

		if (sids.startsWith(",")) {
			sids = sids.substring(1);
		}

		List<String> sqltemp = new ArrayList<>();
		String[] split = sids.split(",");
		for (String str : split) {
			if (StringUtils.isNotBlank(str))
				sqltemp.add(str);
		}

		Map<String, Object> param = new HashMap<>();
		param.put("sids", sqltemp);
		List<AdminMenu> listBySids = adminMenuDao.listBySids(param);

		mess.setData(listBySids);

		return mess;
	}

	public List<AdminMenu> listByParentId(int parentId) {
		return adminMenuDao.selectByParentId(parentId);
	}

	public List<Map<String, Object>> listSubMenus(int parentId) {
		List<AdminMenu> list = listByParentId(parentId);
		List<Map<String, Object>> lm = new ArrayList<Map<String, Object>>();
		if (list != null && list.size() > 0) {
			for (AdminMenu menu : list) {
				Map<String, Object> map = menu2map(menu);
				List<Map<String, Object>> childs = listSubMenus(menu.getId());
				if (childs != null && childs.size() > 0) {
					map.put("children", childs);
					map.put("isParent", true);
				} else {
					map.put("isParent", false);
				}
				lm.add(map);
			}
			return lm;
		} else
			return null;
	}

	public List<AdminMenu> listChilds(int parentId) {
		List<AdminMenu> list = listByParentId(parentId);
		for (AdminMenu menu : list) {
			List<AdminMenu> childs = listByParentId(menu.getId());
			if (childs != null && childs.size() > 0) {
				menu.set("children", childs);
				menu.set("isParent", true);
			} else {
				menu.set("isParent", false);
			}
		}
		return list;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param ids
	 * @param sorts
	 * @return
	 */
	public Message<?> updateSort(String[] ids, String[] sorts) {

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		int length = ids.length;
		for (int i = 0; i < length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", ids[i]);
			map.put("sort", sorts[i]);
			list.add(map);
		}
		adminMenuDao.updateSort(list);
		return Message.fireSuccess();
	}

	public List<Map<String, Object>> listWithCheckedByRoleSid(String roleSid) {
		List<String> sids = adminRoleMenuDao.listMenuSidsByRoleSid(roleSid);
		List<Map<String, Object>> allmenus = listSubMenus(0);
		listWithChecked(sids, allmenus);
		return allmenus;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param sids
	 * @param allmenus
	 */
	@SuppressWarnings("unchecked")
	private void listWithChecked(List<String> sids, List<Map<String, Object>> allmenus) {
		for (Map<String, Object> map : allmenus) {
			Object o = map.get("sid");
			if (o != null) {
				String sid = o.toString();
				if (sids.contains(sid))
					map.put("checked", true);
				else
					map.put("checked", false);
			}
			List<Map<String, Object>> childs = (List<Map<String, Object>>) map.get("children");
			if (childs != null && childs.size() > 0)
				listWithChecked(sids, childs);
		}
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @return
	 */
	public List<Map<String, Object>> listWithAdmin() {
		List<AdminMenu> lm = adminMenuDao.listByAdminSid(ShiroUtils.getUserSid());
		List<Map<String, Object>> list = new ArrayList<>();
		for (AdminMenu menu : lm) {
			if (menu.getParentId() == 0)
				list.add(menu2map(menu));
		}
		upChilds(lm, list);
		return list;
	}

	private List<Map<String, Object>> checkChilds(List<AdminMenu> lm, int parentId) {
		List<Map<String, Object>> list = new ArrayList<>();
		for (AdminMenu menu : lm) {
			if (menu.getParentId() == parentId)
				list.add(menu2map(menu));
		}
		return list;
	}

	private void upChilds(List<AdminMenu> lm, List<Map<String, Object>> list) {
		for (Map<String, Object> map : list) {
			int pid = (int) map.get("id");
			List<Map<String, Object>> childs = checkChilds(lm, pid);
			if (childs != null && !childs.isEmpty()) {
				map.put("children", childs);
				map.put("isParent", true);
				upChilds(lm, childs);
			} else {
				map.put("isParent", false);
			}
		}
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param menu
	 * @return
	 */
	private Map<String, Object> menu2map(AdminMenu menu) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", menu.getId());
		map.put("sid", menu.getSid());
		map.put("name", menu.getName());
		map.put("sort", menu.getSort());
		String icon = menu.getIcon();
		if (StringUtils.isBlank(icon))
			icon = "fa fa-circle-o";
		map.put("_icon", icon);
		map.put("_href", menu.getHref());
		map.put("href", menu.getHref());
		map.put("icon", menu.getIcon());
		map.put("level", menu.getLevel());
		map.put("parentId", menu.getParentId());
		map.put("isShow", menu.getIsShow());
		return map;
	}
}
